<template>
  <div class="shell" v-if="$store.state.infoLoad&&ifLoad">
    <!-- 条件渲染，仅在用户信息加载且组件数据加载完成时显示 -->
    <div class="top">
      <!-- 用户头像 -->
      <img :src="`${$store.state.userInfo.photo}`" alt="">
      <div class="info">
        <div class="i-left">
          <!-- 用户名 -->
          <span class="name">{{ $store.state.userInfo.mname }}</span>
          <!-- 以下是用户信息项 -->
          <span class="info-item">真实姓名：<span>{{ realname }}</span></span>
          <span class="info-item">邮箱：<span>{{ $store.state.userInfo.mail }}</span></span>
          <span class="info-item">地址：<span>{{ $store.state.userInfo.addr }}</span></span>
          <span class="info-item">电话：<span>{{ $store.state.userInfo.tel }}</span></span>
          <span class="info-item intro">简介：<span>{{ intro }}</span></span>
        </div>
        <div class="i-right">
          <!-- 用户等级称号 -->
          <span class="grade"><span>{{ nickIndex }}</span>{{ nicks[nickIndex] }}</span>
          <!-- 编辑信息按钮 -->
          <button @click="$store.commit('switchInfoEdit',true)">编辑信息</button>
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="my-game">
        <span class="label">我的游戏</span>
        <!-- 渲染用户游戏列表 -->
        <div class="games">
          <myGameCard v-for="(v,i) in games" :key="i" :game="v"></myGameCard>
        </div>
      </div>
    </div>
    <!-- 编辑用户信息的子组件 -->
    <infoEdit></infoEdit>
  </div>
</template>

<script>
import infoEdit from '@/components/infoEdit.vue'; // 编辑用户信息组件
import myGameCard from '@/components/myGameCard.vue'; // 游戏卡片组件
import { ElLoading } from 'element-plus' // Element UI加载组件
export default {
  computed:{
    intro(){
      if(this.$store.state.userInfo.introduce=="") return "空空如也 ~ ";
      return this.$store.state.userInfo.introduce;
    },
    realname(){
      if(this.$store.state.userInfo.realname=="") return "未知";
      return this.$store.state.userInfo.realname;
    },
    nickIndex(){
      // this.$store.state.userInfo.birth
      const startDate = new Date("2023-10-05");
      const endDate = new Date();
      // 计算相差的时间（毫秒）
      const timeDiff = endDate.getTime() - startDate.getTime();
      // 将毫秒转换成天数
      const daysDiff = Math.floor((timeDiff / (1000 * 60 * 60 * 24))/3);
      if(daysDiff > 6) return 6;
      return daysDiff;
    }
  },
  data(){
    return{
      games: [],
      orders: [],
      ifLoad: false,
      nicks: ["初出茅庐", "小有名气", "渐入佳境", "声名鹊起", "一举成名", "名震一方", "登峰造极"],
    }
  },
  components:{ 
    infoEdit,
    myGameCard,
  },
  methods: {
    // 获取用户的游戏
    async getAllGames(){
      const that = this;
      await that.$axios.get('mybox/getMybox').then((response) => {
        // console.log(response)
        if (response.status != 200) return that.$tools.alertMsg('系统错误', 'error');
        if (response.data.code == 200) {
          // 初始化一个新的Set用来跟踪出现过的gname值
          const seen = new Set();
          // 过滤response.data.data数组，只保留那些具有唯一gname的对象
          that.games = response.data.data.filter(item => {
            // 如果gname已经出现过，则返回false，否则返回true
            const duplicate = seen.has(item.gname);
            seen.add(item.gname);
            return !duplicate;
          });
          that.games.forEach((item,index)=>{
            // 处理图片和视频字段
            const mediaFields = ['photo', 'photoa', 'photob', 'photoc', 'photod', 'icon', 'video'];
            mediaFields.forEach(field => {
              if (item[field] && !item[field].startsWith('http')) {
                item[field] = `${that.$store.state.baseUrl}/${item[field]}`;
              }
            });
          })
        } else {
          that.$tools.alertMsg('获取数据失败', 'warning', 1500); 
        }
      }).catch(function (error) {
        console.log(error)
      })
    },
    async getUserInfo() {
      const that = this;
      await that.$axios.get('getUserInfo').then((response) => {
        console.log(response)
        if (response.status != 200) return that.$tools.alertMsg('系统错误', 'error');
        if (response.data.code == 200) {
          that.$store.commit('saveUserInfo',response.data.data[0]);
        } else {
          that.$tools.alertMsg('获取用户数据失败', 'warning', 1500); 
        }
      }).catch(function (error) {
        console.log(error)
      })
    }
  },
  async created(){
    const loadOptions = { text: "加载中", background: "rgba(23,29,37,0.7)" };
    this.loadingInstance = ElLoading.service(loadOptions);
    await this.getUserInfo();
    await this.getAllGames();
    this.loadingInstance.close();
    this.ifLoad = true;
  }
  
}
</script>

<style lang="less" scoped>
.shell{
  height: calc(100vh - 72px);
  width: 100%;
  // 顶部样式
  .top{
    max-width: 960px;
    margin: 0px auto;
    margin-top: 10px;
    display: flex;
    align-items: center;
    height: 200px;
    padding: 0px 20px;
    background-color: #172636;
    img{
      width: 170px;
      height: 170px;
      object-fit: cover;
      object-position: center;
    }
    .info{
      width: 100%;
      height: 100%;
      padding: 15px 40px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      
      .i-left{
        display: flex;
        flex-direction: column;
        text-align: left;
        
        width: 70%;
        span{
          padding: 2px 0px;
          color: #888;
          font-size: 15px;
        }
        .name{
          font-size: 19px;
          font-weight: bold;
          color: #eee;
        }
        .info-item{
          span{
            color: #bbb;
          }
        }
        .intro{
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          word-break: break-all; // 添加这行代码
        }
      }
      .i-right{
        width: 30%;
        color: #fff;
        padding: 40px 0px;
        justify-content: space-between;
        display: flex;
        flex-direction: column;
        align-items: center;
        .grade{
          font-size: 20px;
          font-weight: bold;
          span{
            display: inline-block;
            width: 22px;
            height: 22px;
            border-radius: 50%;
            border: 2px solid #666;
            margin-right: 4px;
            text-align: center;
          }
        }
        button{
          margin-top: 20px;
          height: 36px;
          width: 100px;
          border-radius: 8px;
          color: #ddd;
          font-weight: bold;
          background-color: #0e141a;
          flex-shrink: 0;
        }
      }
    }
  }
  // 底部样式
  .bottom{
    max-width: 960px;
    margin: 0px auto;
    margin-top: 20px;
    .my-game{
      display: flex;
      flex-direction: column;
      text-align: left;
      background-color: #28374C;
      margin-bottom: 20px;
      .label{
        color: #aaa;
        padding: 10px 0px 10px 20px;
      }
      .games{

        background-color: #35435B;
      }
    }
  }
}
</style>
